package com.slipper.monitor;

import de.codecentric.boot.admin.server.config.AdminServerProperties;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;

import de.codecentric.boot.admin.server.config.EnableAdminServer;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;
import org.springframework.security.web.csrf.CookieCsrfTokenRepository;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;

@Configuration
@EnableAutoConfiguration
@EnableDiscoveryClient
@EnableAdminServer
public class MonitorApplication {
    public static void main(String[] args) {
        SpringApplication.run(MonitorApplication.class, args);
    }

    @Configuration
    public static class SecuritySecureConfig {
        private final String contextPath;

        public SecuritySecureConfig(AdminServerProperties adminServer) {
            this.contextPath = adminServer.getContextPath();
        }

        @Bean
        public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
            SavedRequestAwareAuthenticationSuccessHandler successHandler = new SavedRequestAwareAuthenticationSuccessHandler();
            successHandler.setTargetUrlParameter("redirectTo");
            successHandler.setDefaultTargetUrl(this.contextPath + "/");

            http.authorizeRequests()
                    .antMatchers(this.contextPath + "/assets/**").permitAll()
                    .antMatchers(this.contextPath + "/login").permitAll()
                    .anyRequest().authenticated()
                    .and()
                    .formLogin().loginPage(this.contextPath + "/login").successHandler(successHandler).and()
                    .logout().logoutUrl(this.contextPath + "/logout").and()
                    .httpBasic().and()
                    .csrf()
                    .csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse())
                    .ignoringRequestMatchers(
                            new AntPathRequestMatcher(this.contextPath + "/instances", HttpMethod.POST.toString()),
                            new AntPathRequestMatcher(this.contextPath + "/instances/*", HttpMethod.DELETE.toString()),
                            new AntPathRequestMatcher(this.contextPath + "/actuator/**")
                    );
            return http.build();
        }
    }
}
